using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Framework.Library.Base.Base;
using Framework.Library.Base.DataAccess;
using Framework.Library.Base.Extensions;
using Framework.Library.Core.Utils;
using Framework.Library.Data.DAL;
using Framework.Library.Data.DAO;
using Framework.Library.Data.DAL.JObject;

namespace Framework.Portal.Layouts.Admin.Components.Roles
{
    public partial class RoleManagement : BaseControl
    {
        public string MENUNAME = string.Empty;

        public RoleManagement()
        {
        }

        public RoleManagement(JSection section)
        {
            MENUNAME = section.title;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                General_GetDefault();
                List<PortalMenu> lstMenu = ManagerFactory.PortalMenuManager.GetAll(Session.WorkingPortal().PORTALID);
                if (lstMenu != null)
                    PortalAccess.LoadMenus(lstMenu, Permission_drpMenu.Items);
            }
        }

        protected void tvwCmds_SelectedNodeChanged(object sender, EventArgs e)
        {
            int curMenuBinding = Convert.ToInt32(tvwCmds.SelectedValue);
            PortalRole role = ManagerFactory.DAOEntity.GetInfo(new PortalRole() { ROLEID = curMenuBinding });
            if (role != null)
            {
                btnMember.Enabled = true;
                btnPermission.Enabled = true;
                General_lblID.Text = role.ROLEID.ToString();
                General_txtRoleName.Text = role.ROLENAME;
                General_txtRoleDescription.Text = role.ROLEDESCRIPTION;
                General_drpRoleParentID.SelectedValue = role.ROLEPARENTID.ToString();
                Member_GetData(role.ROLEID);
                Permission_drpMenu.SelectedIndex = -1;
                if (role.PERMISIONS != "0")
                {
                    string[] lstMenu = role.PERMISIONS.Split(',');
                    foreach (ListItem item in Permission_drpMenu.Items)
                    {
                        foreach (string s in lstMenu)
                        {
                            if (item.Value == s)
                            {
                                item.Selected = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    foreach (ListItem item in Permission_drpMenu.Items)
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        protected void General_btnUpdate_Click(object sender, EventArgs e)
        {
            PortalRole role = General_GetData();
            role.ROLEID = ConvertUtility.ToInt32(General_lblID.Text);
            ManagerFactory.DAOEntity.Update(role);
            General_GetDefault();
            General_lblUpdate.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
        }

        protected void General_btnAdd_Click(object sender, EventArgs e)
        {
            ManagerFactory.DAOEntity.Insert(General_GetData());
            General_GetDefault();
            General_lblUpdate.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
        }

        protected void General_btnDelete_Click(object sender, EventArgs e)
        {
            int ID = Convert.ToInt32(General_lblID.Text);
            ManagerFactory.PortalRoleManager.Delete(ID);
            General_GetDefault();
            General_lblUpdate.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
        }

        protected void General_btnCancel_Click(object sender, EventArgs e)
        {
            General_GetDefault();
            btnMember.Enabled = true;
            btnPermission.Enabled = true;
        }

        private void General_GetDefault()
        {
            General_drpRoleParentID.Items.Clear();
            List<PortalRole> dtRoles = ManagerFactory.PortalRoleManager.GetRoles(Session.WorkingPortal().PORTALID);
            if (dtRoles != null)
            {
                PortalAccess.LoadRoles(dtRoles, General_drpRoleParentID.Items);
                PortalAccess.LoadRoles(dtRoles, tvwCmds.Nodes);
            }
            General_drpRoleParentID.Items.Insert(0, new ListItem("Root", "0"));

            General_txtRoleName.Text = string.Empty;
            General_txtRoleDescription.Text = string.Empty;
            General_drpRoleParentID.SelectedIndex = -1;
        }

        protected void rptUser_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var info = (PortalUser) e.Item.DataItem;
                var lblName = (Label) e.Item.FindControl("lblName");
                var lblSTT = (Label) e.Item.FindControl("lblSTT");

                var btnDelete = (ImageButton) e.Item.FindControl("Label7");
                btnDelete.CommandName = "delete";
                btnDelete.CommandArgument = info.USERID.ToString();

                lblSTT.Text = info.USERID.ToString();
                lblName.Text = info.USERNAME;
            }
        }

        public void rptUser_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int cur = Convert.ToInt32(e.CommandArgument);
            switch (e.CommandName)
            {
                case "delete":
                    ManagerFactory.PortalRoleManager.RemoveUserFromRole(cur, Convert.ToInt32(General_lblID.Text));
                    Member_lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
                    Member_GetData(Convert.ToInt32(General_lblID.Text));
                    break;
                default:
                    break;
            }
        }

        protected void Member_btnAdd_Click(object sender, EventArgs e)
        {
            ManagerFactory.PortalRoleManager.AddUserToRole(Convert.ToInt32(Member_drpUser.SelectedValue),
                                                           Convert.ToInt32(General_lblID.Text));
            Member_lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
            Member_GetData(Convert.ToInt32(General_lblID.Text));
        }

        private void Member_GetData(int roleId)
        {
            List<PortalUser> lstUserinRole = ManagerFactory.PortalUserManager.GetUsers(roleId, Session.WorkingPortal().PORTALID);
            if (lstUserinRole != null)
            {
                rptUser.DataSource = lstUserinRole;
                rptUser.DataBind();
            }
            else
            {
                rptUser.DataSource = null;
                rptUser.DataBind();
            }
            List<PortalUser> lstUsernotinRole = ManagerFactory.PortalUserManager.GetUsersNotInRole(roleId,
                                                                                                   Session.WorkingPortal().PORTALID);
            if (lstUsernotinRole != null)
            {
                Member_btnAdd.Enabled = true;
                PortalAccess.LoadUsers(lstUsernotinRole, Member_drpUser.Items);
            }
            else
                Member_btnAdd.Enabled = false;
        }

        protected void Permission_btnUpdate_Click(object sender, EventArgs e)
        {
            string permisionZoneCollection = string.Empty;
            int i = 0;
            foreach (ListItem item in Permission_drpMenu.Items)
            {
                if (item.Selected)
                {
                    i++;
                    permisionZoneCollection += item.Value + ",";
                }
            }

            if (i == Permission_drpMenu.Items.Count)
                permisionZoneCollection = "0";
            else
                permisionZoneCollection = permisionZoneCollection.TrimEnd(',');
            ManagerFactory.PortalRoleManager.UpdatePermission(Convert.ToInt32(General_lblID.Text),
                                                              permisionZoneCollection);
            Permission_lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
        }

        private PortalRole General_GetData()
        {
            var role = new PortalRole();
            role.ROLENAME = General_txtRoleName.Text;
            role.ROLEDESCRIPTION = General_txtRoleDescription.Text;
            role.ROLEPARENTID = ConvertUtility.ToInt32(General_drpRoleParentID.SelectedValue);
            role.PORTALID = Session.WorkingPortal().PORTALID;
            return role;
        }

        protected void ActiveTab(object sender, EventArgs e)
        {
            var sends = sender as LinkButton;
            if (sends != null)
            {
                panelGeneral.Visible = false;
                btnGeneral.CssClass = "tab";
                panelMember.Visible = false;
                btnMember.CssClass = "tab";
                panelPermission.Visible = false;
                btnPermission.CssClass = "tab";
                switch (sends.CommandArgument)
                {
                    case "1":
                        panelGeneral.Visible = true;
                        btnGeneral.CssClass = "tab tabActive";
                        break;
                    case "2":
                        panelMember.Visible = true;
                        btnMember.CssClass = "tab tabActive";
                        break;
                    case "3":
                        panelPermission.Visible = true;
                        btnPermission.CssClass = "tab tabActive";
                        break;
                    default:
                        break;
                }
            }
        }
    }
}